package distributed.lock.expand;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import distributed.lock.factory.ZookeeperFactory;
import distributed.lock.util.IpUtil;

/**
 * @comment 基于zookeeper的分布式锁
 * @date 2015年11月9日 上午11:27:10
 * @author zhouxiao
 * @qq 772716714
 * @version 1.0
 */
public class ZookeeperLock implements Lock {

	private static Logger logger = LoggerFactory.getLogger(ZookeeperLock.class);

	private ZookeeperFactory zookeeperFactory;

	private static final String IP = IpUtil.getIp();

	public void lock(String key, String value) {
		zookeeperFactory = new ZookeeperFactory();
		try {
			zookeeperFactory.connect();
			while (true) {
				logger.warn("lock key: " + key);
				if (!zookeeperFactory.exists(key)) {
					boolean b = true;
					try {
						zookeeperFactory.create(key, value);
					} catch (Exception e) {
						b = false;
					}
					if (b) {
						logger.warn("set lock success, key: " + key + "  on ip " + IP);
						break;
					}

				} else {
					logger.warn("set lock faile : " + key + " locked by another business on ip " + IP);
					Thread.sleep(100);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void unLock(String key) {
		try {
			zookeeperFactory.close();
			logger.warn("delete lock  : " + key + " on ip " + IP);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
